package product

import (
	"context"
	"gitee.com/zyw0605688_admin/gozero/product_service/internal/svc"
	"gitee.com/zyw0605688_admin/gozero/product_service/internal/types"
	"gitee.com/zyw0605688_admin/gozero/product_service/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductUpdateLogic {
	return &ProductUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductUpdateLogic) ProductUpdate(req *types.ProductUpdateRequest) (resp *types.ProductUpdateResponse, err error) {
	// 先根据id查出数据库里的结果
	item := model.Product{}
	err = l.svcCtx.DB.Where("id = ?", req.Id).First(&item).Error
	if err != nil {
		return
	}
	// 根据参数修改件结果
	if req.ProductName != nil {
		item.ProductName = *req.ProductName
	}
	if req.ProductPrice != nil {
		item.ProductPrice = *req.ProductPrice
	}
	if req.ProductTypeId != nil {
		item.ProductTypeId = *req.ProductTypeId
	}
	if req.ProductDesc != nil {
		item.ProductDesc = *req.ProductDesc
	}
	if req.CreatedAt != nil {
		item.CreatedAt = *req.CreatedAt
	}
	// 保存回数据库
	err = l.svcCtx.DB.Save(&item).Error
	if err != nil {
		return
	}
	productTypeName := ""
	err = l.svcCtx.DB.Raw("select product_type_name from product_type where id = ?", item.ProductTypeId).Scan(&productTypeName).Error
	if err != nil {
		return nil, err
	}
	resp = &types.ProductUpdateResponse{
		Id:              item.Id,
		ProductName:     item.ProductName,
		ProductPrice:    item.ProductPrice,
		ProductTypeId:   item.ProductTypeId,
		ProductTypeName: productTypeName,
		ProductDesc:     item.ProductDesc,
		CreatedAt:       item.CreatedAt,
	}

	return
}
